package org.bt.common.validator;

import org.apache.commons.lang3.StringUtils;
import org.bt.common.utils.AppUtil;
import org.bt.common.validator.aspect.Length;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

/**
 * 字符串长度校验
 * <p>
 * Created on 2020/1/10
 *
 * @author tongw
 */
public class LengthValidator implements ConstraintValidator<Length, String> {

    private int max;
    private int min;

    @Override
    public void initialize(Length constraintAnnotation) {
        max = constraintAnnotation.max();
        min = constraintAnnotation.min();
    }

    @Override
    public boolean isValid(String value, ConstraintValidatorContext constraintValidatorContext) {
        int length = 0;
        if (StringUtils.isNotEmpty(value)) {
            length = AppUtil.wordLength(value);
        }
        return length >= min && length <= max;

    }
}
